package rpt

import (
	"context"
	"gitee.com/alex_li/amazon-rpt/cmd/rpt/process/common"
	"gitee.com/alex_li/amazon-rpt/internal/db"
	"github.com/lishimeng/app-starter"
	"github.com/lishimeng/go-log"
	"time"
)

func UpdateRpt(ctx context.Context) {

	for {
		select {
		case <-ctx.Done():
			return
		case <-time.After(time.Second * 23):
			updateAllRpt()
		}
	}
}

func updateAllRpt() {
	var err error
	var list []db.AmazonRpt
	_, err = app.GetOrm().Context.
		QueryTable(new(db.AmazonRpt)).
		Filter("Status__in", db.RptStatusSubmit, db.RptStatusProcessing).
		Filter("mtime__lt", time.Now().Add(-time.Minute*10)).
		Limit(1).All(&list)
	if err != nil {
		log.Info(err)
		return
	}
	if len(list) == 0 {
		//log.Info("no rpt")
		return
	}

	var r = list[0]
	client, err := common.GetMyClient(r.ClientId)
	if err != nil {
		log.Info(err)
		return
	}
	sdk, err := common.CreateSdk(client)
	if err != nil {
		log.Info(err)
		return
	}
	res, err := sdk.ReportStatus(r.RptId)
	if err != nil {
		log.Info(err)
		return
	}
	updateRptStatus(client.ClientId, res)
}
